// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
const db = cloud.database()
const _ = db.command
const $ = db.command.aggregate

async function addStadium(addData) {
  addData['stadium_state'] = 1;
  addData.stadium_geo = db.Geo.Point(addData.stadium_geo.longitude, addData.stadium_geo.latitude);
  addData.appointment_period = parseInt(addData.appointment_period);
  return await db.collection('tb_stadium').add({ data: addData });
}

async function searchStadiumList(searchText, searchData) {
  const res = await db.collection('tb_stadium').aggregate()
    .match(searchData)
    .match(
      _.or([
        { stadium_name: new RegExp(searchText, 'i') },
        { stadium_addr: new RegExp(searchText, 'i') },
      ])
    )
    .limit(200)
    .end();
  return res.list;
}

async function updateStadium(stadium_id, updData) {
  if (typeof (updData.appointment_period) !== 'undefined') updData.appointment_period = parseInt(updData.appointment_period);
  return await db.collection('tb_stadium')
    .where({ _id: stadium_id })
    .update({ data: updData })
}

async function findOne(stadium_id) {
  const res = await db.collection('tb_stadium').aggregate()
    .match({ _id: stadium_id })
    .end();
  return res.list;
}

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  let errMsg = ''
  if (event.funcName == 'insert') {
    try {
      await addStadium(event.addData);
    } catch (error) {
      errMsg = 'Insert fail!'
    }
  } else if (event.funcName == 'query') {
    return await searchStadiumList(event.searchText, event.searchData);
  } else if (event.funcName == 'update') {
    return await updateStadium(event.stadium_id, event.updData);
  } else if (event.funcName == 'queryOne') {
    return await findOne(event.stadium_id)
  }
  return {
    event,
    openid: wxContext.OPENID,
    appid: wxContext.APPID,
    unionid: wxContext.UNIONID,
    errMsg: errMsg,
  }
}